package com.guiji.text2video.fastvideo.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @program: text2video
 * @description: 判断编码工具类
 * @author: gaoX
 * @create: 2021-06-24 18:24
 **/
public class CharsetUtils {

    public static File convert(File f) {
        Charset charset = detectCharset(f);
        if(charset==null){
            return f;
        }
        if(!charset.equals(CharsetUtil.CHARSET_UTF_8)){
            f  = FileUtil.convertCharset(f, charset, CharsetUtil.CHARSET_UTF_8);
            return f;
        }
        return f;
    }


    public static Charset detectCharset(File f) {

        String[] charsets = {CharsetUtil.UTF_8, CharsetUtil.ISO_8859_1,CharsetUtil.GBK, "GB2312", "UTF-16","Unicode"};
        Charset charset = null;

        for (String charsetName : charsets) {
            charset = detectCharset(f, Charset.forName(charsetName));
            if (charset != null) {
                break;
            }
        }

        return charset;
    }

    private static Charset detectCharset(File f, Charset charset) {
        try {
            BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));

            CharsetDecoder decoder = charset.newDecoder();
            decoder.reset();

            byte[] buffer = new byte[512];
            boolean identified = false;
            while ((input.read(buffer) != -1) && (!identified)) {
                identified = identify(buffer, decoder);
            }

            input.close();

            if (identified) {
                return charset;
            } else {
                return null;
            }

        } catch (Exception e) {
            return null;
        }
    }

    private static boolean identify(byte[] bytes, CharsetDecoder decoder) {
        try {
            decoder.decode(ByteBuffer.wrap(bytes));
        } catch (CharacterCodingException e) {
            return false;
        }
        return true;
    }
}
